<template>
    <div class="common-layout">
        <el-container>
            <el-main>
                <!-- 按钮组件 -->
                <div class="btn">
                    <span>角色名称:</span><el-input clearable v-model="role.name" />
                    <span>描述信息:</span><el-input clearable v-model="role.desc" />
                    <el-button type="primary" :icon="Plus" @click="add" v-permissions="'sys:role:create'">添加</el-button>
                </div>
                <!-- 表格组件 -->
                <div class="tab">
                    <el-table :data="rolesData" style="width: 100%" border>
                        <el-table-column prop="name" label="角色名称" />
                        <el-table-column prop="desc" label="说明" />
                        <el-table-column label="操作时间">
                            <template #default="scope">
                                <div v-if="scope.$index">
                                    <el-button type="primary" v-permissions="'sys:role:update'" @click="handleEdit(scope.row)">修改</el-button>
                                    <el-button type="primary" @click="handleImpower(scope.row)">授权</el-button>
                                    <el-button type="danger" v-permissions="'sys:role:delete'"
                                        @click="handleDelete(scope.$index, scope.row)">删除</el-button>
                                </div>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
                <!-- 修改角色弹出框 -->
                <el-dialog v-model="dialogFormVisible" title="修改信息">
                    <el-form :model="form">
                        <el-form-item label="角色名称:">
                            <el-input v-model="form.name" autocomplete="off" />
                        </el-form-item>
                        <el-form-item label="描述信息:">
                            <el-input v-model="form.desc" autocomplete="off" />
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" @click="cofrim">修改</el-button>
                        </el-form-item>
                    </el-form>
                </el-dialog>
                <!-- 授权弹出框 -->
                <el-dialog v-model="dialogFormVisibles" title="权限配置" style="width: 30vw;">
                    <el-tree :data="limitData" show-checkbox node-key="id" accordion ref="treeRef">
                        <!-- node--当前节点对象,data--当前节点 -->
                        <template #default="{ node, data }">
                            <span class="custom-tree-node">
                                <span>{{ node.label }}</span>
                                <span v-if="data.api">{{ data.id }}</span>
                            </span>
                        </template>
                    </el-tree>
                    <template #footer>
                        <span class="dialog-footer">
                            <el-button @click="dialogFormVisibles = false">取消</el-button>
                            <el-button type="primary" @click="getCheckedKeys">
                                确定
                            </el-button>
                        </span>
                    </template>
                </el-dialog>
                <!-- 分页组件 -->
                <Pagination @page-change="handlePagehange" v-bind="datas" />
            </el-main>
        </el-container>
    </div>
</template>
<script lang="ts" setup>
import type { roles, User, Tree } from '@/type/params'//引入类型
import { ref, onMounted, nextTick, reactive } from 'vue'//引入响应式，生命周期
import { Plus } from '@element-plus/icons-vue'//引入图标
import { post,get } from '@/untils/request'//引入请求方式
import Pagination from '@/components/Pagination.vue' //引入分页组件
import { ElMessage } from 'element-plus'//引入消息提示框

const rolesData = ref([])//角色管理列表
const datas = ref<roles>({//渲染页面数据
    total: 0,
    page: 1,//当前页面
    limit: 10,//一页面所显示的条数
    _gp: 'admin.role',
    _mt: 'list',
})
const form = reactive({//修改角色数据
    name: '',//角色名称
    desc: '',//角色描述
    status: 1//角色状态
})
const role = reactive({//添加角色数据
    name: '',
    desc: '',
    status: 1
})
const dialogFormVisible = ref(false)//修改角色弹框，默认隐藏状态
const dialogFormVisibles = ref(false)//权限弹框，默认隐藏状态
const limitData = ref<Tree[]>([])//权限列表

const treeRef = ref()
//生命周期---挂载后
onMounted(() => {
    init()
})
const init = (): void => {//渲染角色管理列表
    get(datas.value).then(res => {
        let { items } = res.data
        let { data } = res
        rolesData.value = items//赋值表格
        datas.value.total = data.total//赋值总条数
    }).catch(err => {
        console.log(err);
    })
};

//添加
const add = (): void => {
    if (role.name == '') {
        ElMessage.warning('添加角色名称不能为空')
        return
    }
    let adds = {
        _gp: 'admin.role',
        _mt: 'create',
        role: JSON.stringify({//角色对象转json形式,并进行传值
            ...role
        })
    }
    post(adds).then(res => {
        let { errno, errmsg } = res
        if (200 == errno) {
            console.log(res)
            ElMessage.success(errmsg)
            role.name = '',//清空输入框值，方便下次添加
                role.desc = '',
                init()
        } else {
            ElMessage.error(errmsg)
        }
    }).catch(err => {
        console.log(err);
        ElMessage.info('添加失败')
    })
}

//修改
const handleEdit = (row: User): void => {
    dialogFormVisible.value = true//显示弹弹出框
    Object.assign(form, row)//Object.assign()方法用于合并对象
}
//修改确定按钮
const cofrim = (): void => {
    if (form.name) {
        let edits = {
            _gp: 'admin.role',
            _mt: 'update',
            role: JSON.stringify({//JSON.stringify方法转换为json形式
                ...form
            })
        }
        post(edits).then(res => {
            console.log(res);
            ElMessage.success('修改成功')
            dialogFormVisible.value = false//隐藏弹弹出框
            init()//刷新
        }).catch(err => {
            console.log(err);
            ElMessage.info('修改失败')
        })
    } else {
        ElMessage.error('角色名称不能为空')
    }
}
let roleId = ref(0)
//渲染权限列表
const handleImpower = (row: User): void => {
    roleId.value = row.id
    limitData.value.length = 0
    console.log(row.id)
    dialogFormVisibles.value = true//显示权限弹出框
    const permission = {//删除角色管理数据
        _gp: 'admin.role',
        _mt: 'permissionList',
        roleId: row.id,//将当前对象的id赋值给角色id(roleId)
    }
    post( permission).then(res => {
        let { systemPermissions, assignedPermissions } = res.data
        limitData.value = systemPermissions//赋值
        nextTick(() => {
            treeRef.value!.setCheckedKeys(assignedPermissions)//设置节点
        })
    }).catch(err => {
        console.log(err);
    })
}

//确定按钮--给角色配置权限
const getCheckedKeys = (): void => {//获取节点
    let permissions = treeRef.value!.getCheckedKeys(true)
    let checks = {
        _gp: "admin.role",
        _mt: "permissionSet",
        roleSetPermissionDTO: JSON.stringify({ //对授权对象进行JSON.stringify()转型
            roleId: roleId.value,
            permissions
        })
    }
    post(checks).then(res => {
        console.log(res, 99);
        ElMessage.success('配置成功')
        treeRef.value!.getCheckedKeys(true)//获取checkbox
        dialogFormVisibles.value = false//隐藏权限弹出框
    }).catch(err => {
        console.log(err);
        ElMessage.info('配置失败')
    })
}

//删除
const handleDelete = (index: number, row: User): void => {
    console.log(index, row)
    const delts = {//删除角色管理数据
        _gp: 'admin.role',
        _mt: 'delete',
        roleId: row.id,//将当前对象的id赋值给角色id(roleId)
    }
    //@ts-ignore
    ElMessageBox.confirm(
        '确定要删除吗?',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消'
        }
    )
        .then(() => {
            get(delts).then(res => {
                console.log(res);
                rolesData.value.splice(index, 1)//点击确定进入请求，请求成功删除当前行
                ElMessage.success('删除成功')
            }).catch(err => {
                console.log(err);
                ElMessage.info('删除失败')
            })
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '取消删除',
            })
        })
}
//分页
const handlePagehange = (s: { page: number, limit: number }): void => {
    datas.value.page = s.page //赋值当前页面
    datas.value.limit = s.limit//赋值一页面所限制显示的条数
    init()//刷新
}

</script>
<style lang="less" scoped>
.el-container {
    font-size: 14px;

    .btn {
        width: 100%;
        display: flex;
        align-items: center;

        span {
            margin-right: 10px;
        }

        .el-input {
            width: 200px;
            margin-right: 10px;
        }
    }

    .btn,
    .tab {
        margin-bottom: 20px;
    }

    .el-dialog {
        .el-form {
            width: 100%;
            display: flex;
            align-items: center;

            .el-input {
                margin-right: 15px;
            }
        }
    }
}
</style>